﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MvcDeviceManager.Models;
using MvcDeviceManager.Service;
using MvcDeviceManager.Filter;

namespace MvcDeviceManager.Controllers
{
    public class RoleAuthorityController : Controller
    {
        //
        // GET: /RoleAuthority/
        MenuActionService menuActionService=new MenuActionService();
        RoleAuthorityService roleAuthorityService = new RoleAuthorityService();
        [AuthorizeFilter]
        public ActionResult Index()
        {
            string[] roles = Roles.GetAllRoles();
            ViewBag.role = new SelectList(roles);
            return View();
        }
        //[AuthorizeFilter]
        public ActionResult RoleAuthoritys(string role)
        {
           IList<MenuAction> actions= menuActionService.allMenuAction();
           IList<ViewModels.RoleAuthority> list = new List<ViewModels.RoleAuthority>(actions.Count);
           IList<RoleAuthority> rolesList = roleAuthorityService.listRoleAuthority(role);
           ViewModels.RoleAuthority ra;
           foreach (MenuAction ma in actions)
           {
               ra = new ViewModels.RoleAuthority();
               ra.Controller = ma.Controller;
               ra.ActionId = ma.ActionId;
               ra.ActionName = ma.ActionName;
               foreach (RoleAuthority rat in rolesList)
               {
                   if (rat.ActionId.Equals(ma.ActionId) && rat.Controller.Equals(ma.Controller))
                   {
                       ra.HasAuthority = true;
                       break;
                   }
               }
               list.Add(ra);
           }
           return Json(list);
        }
        [AuthorizeFilter]
        public ActionResult SubmitChange(FormCollection form) {
            string role = form["role"];
            //if (role.Equals("admin"))
            //{
            //    return Json(new { error = "对不起，角色admin不能执行此操作！" });
            //}
            string Authoritys = form["Authority"];
            IList<RoleAuthority> list = new List<RoleAuthority>();
            if (Authoritys != null)
            {
                char[] sp = new char[] { ',' };
                string[] controll = Authoritys.Split(sp);
                sp = new char[] { ':' };
                RoleAuthority ra;
                string[] actions;
                foreach (string con in controll)
                {
                    actions = con.Split(sp);
                    ra = new RoleAuthority();
                    ra.Role = role;
                    ra.Controller = actions[0];
                    ra.ActionId = actions[1];
                    list.Add(ra);
                }
            }
            roleAuthorityService.updateRoleAuthority(role, list);
            return Json("恭喜你修改成功！");
        }
    }
}
